package cn.gz.coolshark.controller;

import cn.gz.coolshark.mapper.UserMapper;
import cn.gz.coolshark.pojo.dto.UserLoginDTO;
import cn.gz.coolshark.pojo.vo.UserVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;

@RestController
public class UserController {
    @Autowired
    private UserMapper userMapper;

    @RequestMapping("/login")
    public int login(@RequestBody UserLoginDTO user, HttpSession session){
        UserVO userVO = userMapper.selectByUsername(user.getUsername());
        if(userVO==null){
            return 3;//用户名不存在
        }
        if(userVO.getPassword().equals(user.getPassword())){
            //登录成功后把用户对象存入Session
            userVO.setPassword("");
            session.setAttribute("user",userVO);
            return 1;//用户名和密码都对
        }
        return 2;//用户名对，密码错
    }

    @RequestMapping("/logout")
    public void remove(HttpSession session){
        session.removeAttribute("user");
    }

    @RequestMapping("/currentUser")
    public UserVO currentUser(HttpSession session){
       return (UserVO) session.getAttribute("user");
    }
}
